<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="queryParams.messageType" placeholder="请选择消息类型" clearable>
            <el-option
              v-for="dict in messageTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重要等级" prop="importance">
          <el-select v-model="queryParams.importance" placeholder="请选择重要等级" clearable>
            <el-option
              v-for="dict in importanceOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="阅读状态" prop="readStatus">
          <el-select v-model="queryParams.readStatus" placeholder="请选择阅读状态" clearable>
            <el-option label="未读" value="0" />
            <el-option label="已读" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-check"
            :disabled="multiple"
            @click="handleBatchMarkRead"
            v-hasPermi="['system:message:edit']"
          >标记已读</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-search"
            @click="handleUnreadMessage"
          >未读消息</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-setting"
            @click="handleNotifyConfig"
          >通知设置</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 消息列表 -->
      <el-table
        v-loading="loading"
        :data="messageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="isSelectable"/>
        <el-table-column label="消息类型" align="center" prop="messageType" width="120">
          <template slot-scope="scope">
            {{ getMessageType(scope.row.messageType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="重要等级"
          align="center"
          prop="importance"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.importance === '1' ? 'danger' : scope.row.importance === '2' ? 'warning' : 'info'">
              {{ getImportance(scope.row.importance) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="标题"
          align="left"
          prop="title"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template slot-scope="scope">
            <span
              :class="{ 'unread': scope.row.readStatus === '0' }"
              @click="handleView(scope.row)"
              style="cursor: pointer;"
            >{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column
          label="状态"
          align="center"
          prop="readStatus"
          width="80"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.readStatus === '0' ? 'danger' : 'success'" size="mini">
              {{ scope.row.readStatus === '0' ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              v-if="scope.row.readStatus === '0'"
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleMarkRead(scope.row)"
            >已读</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 消息详情弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <div class="message-detail">
        <h3>{{ form.title }}</h3>
        <div class="message-meta">
          <span>
            <i class="el-icon-message"></i>
            {{ getMessageType(form.messageType) }}
          </span>
          <span>
            <i class="el-icon-warning" :class="form.importance"></i>
            {{ getImportance(form.importance) }}
          </span>
          <span>
            <i class="el-icon-time"></i>
            {{ form.createTime }}
          </span>
        </div>
        <div class="message-content" v-html="form.content"></div>
      </div>
    </el-dialog>

    <!-- 通知设置弹窗 -->
    <el-dialog title="通知设置" :visible.sync="configOpen" width="500px" append-to-body>
      <el-form ref="configForm" :model="notifyConfig" label-width="100px">
        <el-form-item label="开启提示音">
          <el-switch v-model="notifyConfig.soundEnabled"/>
        </el-form-item>
        <el-form-item label="提示音类型">
          <el-select v-model="notifyConfig.soundType" :disabled="!notifyConfig.soundEnabled">
            <el-option label="提示音1" value="notify1"/>
            <el-option label="提示音2" value="notify2"/>
            <el-option label="提示音3" value="notify3"/>
          </el-select>
          <el-button 
            type="text" 
            icon="el-icon-video-play" 
            :disabled="!notifyConfig.soundEnabled"
            @click="playSound(notifyConfig.soundType)"
          >试听</el-button>
        </el-form-item>
        <el-form-item label="提示框时长">
          <el-input-number 
            v-model="notifyConfig.duration" 
            :min="0" 
            :max="300000" 
            :step="1000"
          >
          </el-input-number>
          毫秒 (0表示不自动关闭)
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveNotifyConfig">确 定</el-button>
        <el-button @click="configOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMessage, getMessage, markRead, markAllRead } from "@/api/system/message";
import { getConfigKey,updateConfig } from "@/api/system/config";
export default {  
  name: "Message",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      messageList: [],
      // 弹出层标题
      title: "消息详情",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        messageType: null,
        importance: null,
        readStatus: null
      },
      // 表单参数
      form: {},
      // 消息类型选项
      messageTypeOptions: [
        {
          dictValue: '1',
          dictLabel: '系统消息'
        },
        {
          dictValue: '2',
          dictLabel: '订单消息'
        },
        {
          dictValue: '3',
          dictLabel: '行程消息'
        }
      ],
      // 重要等级选项
      importanceOptions: [
        {
          dictValue: '1',
          dictLabel: '紧急'
        },
        {
          dictValue: '2',
          dictLabel: '重要'
        },
        {
          dictValue: '3',
          dictLabel: '普通'
        }
      ],
      configOpen: false,
      notifyConfig: {
        soundEnabled: true,
        soundType: 'notify1',
        duration: 5000
      },
      audioMap: new Map() // 用于存储预加载的音频
    };
  },
  created() {
    this.getList();
    this.preloadAudios(); // 预加载音频
    // 监听刷新消息事件
    this.$bus.$on('refresh-message-data', this.getList);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    this.$bus.$off('refresh-message-data', this.getList);
  },
  methods: {
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      listMessage(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.messageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 未读消息 */
    handleUnreadMessage() {
      this.queryParams.readStatus = '0';
      this.getList();
    },
    /** 获取消息类型 */
    getMessageType(messageType) {
      return this.messageTypeOptions.find(item => item.dictValue === messageType)?.dictLabel || '未知';
    },
    /** 获取重要等级 */
    getImportance(importance) { 
      return this.importanceOptions.find(item => item.dictValue === importance)?.dictLabel || '未知';
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 表格行是否可选择 */
    isSelectable(row) {
      return row.readStatus === '0' // 只允许选择未读消息
    },
    /** 选择条数触发 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.messageId)
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      getMessage(row.messageId).then(response => {
        this.form = response.data;
        this.open = true;
        // 如果是未读消息，标记为已读
        if (row.readStatus === '0') {
          this.handleMarkRead(row, true);
        }
      });
    },
    /** 标记已读操作 */
    handleMarkRead(row, needRefresh = true) {
      markRead(row.messageId).then(response => {
        this.$modal.msgSuccess("标记成功");
        if (needRefresh) {
          this.getList();
        }
      });
    },
    /** 全部已读操作 */
    handleMarkAllRead() {
      this.$modal.confirm('是否确认将全部消息标记为已读？').then(() => {
        markAllRead().then(response => {
          this.$modal.msgSuccess("标记成功");
          this.getList();
        });
      });
    },
    /** 批量标记已读操作 */
    handleBatchMarkRead() {
      const messageIds = this.ids
      if (messageIds.length === 0) {
        this.$modal.msgError("请选择要标记的未读消息")
        return
      }
      this.$modal.confirm('是否确认标记选中的' + messageIds.length + '条消息为已读？').then(() => {
        return markRead(messageIds.join(','))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("标记成功")
      }).catch(() => {})
    },
    /** 打开通知设置 */
    handleNotifyConfig() {
      getConfigKey('sys.notice.soundType').then(response => {
        this.notifyConfig = response.msg?JSON.parse(response.msg):{};
        this.configOpen = true;
      });
    },
    /** 试听提示音 */
    playSound(type) {
      const audio = this.audioMap.get(type);
      if (audio) {
        audio.currentTime = 0; // 重置播放位置
        const playPromise = audio.play();
        if (playPromise) {
          playPromise.catch(error => {
            console.log('音频播放失败:', error);
          });
        }
      }
    },
    /** 保存通知设置 */
    saveNotifyConfig() {
      updateConfig({
        configId:100,
        configName:'消息配置',
        configKey:'sys.notice.soundType',
        configValue:JSON.stringify(this.notifyConfig)
      }).then(() => {
        this.$modal.msgSuccess("保存成功");
        this.configOpen = false;
      });
    },
    // 预加载所有音频文件
    preloadAudios() {
      const audioTypes = ['notify1', 'notify2', 'notify3'];
      audioTypes.forEach(type => {
        const audio = new Audio(require(`@/assets/sounds/${type}.mp3`));
        audio.load(); // 预加载
        this.audioMap.set(type, audio);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.message-detail {
  background-color: #fff;
  border-radius: 4px;

  h3 {
    margin: 0 0 15px 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    line-height: 1.4;
  }

  .message-meta {
    color: #909399;
    font-size: 13px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #EBEEF5;

    span {
      margin-right: 20px;
      display: inline-flex;
      align-items: center;

      i {
        margin-right: 5px;
        font-size: 16px;

        &.el-icon-warning {
          &[class='1'] { color: #F56C6C; }  // 紧急
          &[class='2'] { color: #E6A23C; }  // 重要
          &[class='3'] { color: #909399; }  // 普通
        }
      }
    }
  }

  .message-content {
    line-height: 1.8;
    font-size: 14px;
    color: #606266;
    padding: 10px;
    background-color: #FAFAFA;
    border-radius: 4px;
    min-height: 100px;
    white-space: pre-wrap;  // 保留换行和空格

    p {
      margin: 0 0 10px;
      &:last-child {
        margin-bottom: 0;
      }
    }

    a {
      color: #409EFF;
      text-decoration: none;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// 未读消息样式
.unread {
  font-weight: bold;
  color: #303133;
}

// 弹窗和表格样式覆盖
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #EBEEF5;
  }

  .el-dialog__title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #EBEEF5;
  }
}

:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #F5F7FA;
      color: #606266;
      font-weight: 600;
    }
  }

  .el-table__row {
    td {
      padding: 8px 0;
    }
  }
}

// 表单样式
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 18px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-form-item__label {
    font-weight: normal;
    color: #606266;
  }
}

// 按钮样式
:deep(.el-button) {
  &.el-button--text {
    padding: 0;
    height: auto;
    line-height: inherit;
  }
}
</style> 